#include <stdint.h>
#include "config.h"
#include "apitrans.h"
#include "result.h"
#include "arq_cmd.h"
#include "android.h"
#include "devapi.h"

#if defined (_SUPPORT_ANDROID_SEC)

S_ANDROID_CTL *andriod;

int init_android()
{
	
	return 0;
}

int init_dex_arrary()
{
	S_DEX_CTL  dex;
	int i = 0;

	for(i=0; i < MAX_DEX_CACHE_NUM;i++){
		memset(&dex,0xff,sizeof(S_DEX_CTL));
		android_read(DEX_CACHE_OFFSET + i*sizeof(S_DEX_CTL),&dex,sizeof(S_DEX_CTL));
		if(dex.dex_flag != DEX_FLAG){
			printf("init %d\n",i);
			dex.dex_flag = DEX_FLAG;
			dex.rw_flag = DEX_WRITE_READ;
		        android_write(DEX_CACHE_OFFSET + i*sizeof(S_DEX_CTL),&dex,sizeof(S_DEX_CTL));
		}
	}
	return 0;
}

int check_dex_file(S_DEX_CTL * cache){

	S_DEX_CTL  dex;
	int i = 0;
	int rw_index = 0;
	
	for(i=0; i < MAX_DEX_CACHE_NUM;i++){
		memset(&dex,0xff,sizeof(S_DEX_CTL));
		android_read(DEX_CACHE_OFFSET + i*sizeof(S_DEX_CTL),&dex,sizeof(S_DEX_CTL));
		if((dex.rw_flag == DEX_ONLY_READ)&& \
			((memcmp(dex.name,cache->name,PKG_NAME_MAX)== 0))){
				if(memcmp(dex.sha2,cache->sha2,32)!= 0){
					printf(" %s  fail \n",dex.name);
					int cmd = 0x1;
					android_write(ANDROID_ERROR_OFFSET,cmd,ANDROID_ERROR_LEN);
					buzzer_start();
					mdelay(50);
					reset();
					return DEX_CACHE_FAIL;
				}else{
					printf("%s succ\n",dex.name);
					return DEX_CACHE_SUCC;
				}
		}
		if(dex.rw_flag == DEX_WRITE_READ){
			rw_index = i;
		}
	}
	android_read(DEX_CACHE_OFFSET + rw_index*sizeof(S_DEX_CTL),&dex,sizeof(S_DEX_CTL));

	
	printf("add  = %d[%d], %s\n",rw_index,dex.rw_flag,dex.name);
	
	if(dex.rw_flag == DEX_WRITE_READ)
	{
		memset(&dex,0,sizeof(S_DEX_CTL));
		dex.rw_flag = DEX_ONLY_READ;
		dex.dex_flag = DEX_FLAG;
		memcpy(dex.name,cache->name,PKG_NAME_MAX);
		memcpy(dex.sha2,cache->sha2,32);
		android_write(DEX_CACHE_OFFSET + rw_index*sizeof(S_DEX_CTL),&dex,sizeof(S_DEX_CTL));

		printf("add[%d] %s \n",rw_index,dex.name);
	}
	
	return 0;
}

int rm_dex_file(char * name){

	S_DEX_CTL  dex;
	int i = 0;

	for(i=0; i < MAX_DEX_CACHE_NUM;i++){
		memset(&dex,0,sizeof(S_DEX_CTL));
		android_read(DEX_CACHE_OFFSET + i*sizeof(S_DEX_CTL),&dex,sizeof(S_DEX_CTL));
		if(memcmp(dex.name,name,PKG_NAME_MAX)== 0){
		    dex.rw_flag = DEX_WRITE_READ;	
		     memset(dex.name,0xff,PKG_NAME_MAX);
		     android_write(DEX_CACHE_OFFSET + i*sizeof(S_DEX_CTL),&dex,sizeof(S_DEX_CTL));
			 printf("rm %s \n",name);
		}
	}
	
	return 0;
}	

#endif

